package com.hzsai.mininote.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.MappedInterceptor;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.util.Locale;

/**
 * hzsai 2020/1/14
 * usage:
 **/
@Configuration
public class MyWebMvcInterceptor implements WebMvcConfigurer {

    private LocaleChangeInterceptor lci = null;

    /**
     * Add Spring MVC lifecycle interceptors for pre- and post-processing of
     * controller method invocations. Interceptors can be registered to apply
     * to all requests or be limited to a subset of URL patterns.
     * <p><strong>Note</strong> that interceptors registered here only apply to
     * controllers and not to resource handler requests. To intercept requests for
     * static resources either declare a
     * {@link MappedInterceptor MappedInterceptor}
     * bean or switch to advanced configuration mode by extending
     * {@link WebMvcConfigurationSupport
     * WebMvcConfigurationSupport} and then override {@code resourceHandlerMapping}.
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration ir1 = registry.addInterceptor(localeChangeInterceptor());
//        ir1.addPathPatterns("/*");
    }

    /**
     * 添加国际化语言拦截器
     * 主要在前端控制器里面进行拦截请求地址里面的参数?language=zh_CN这样的参数
     * 进而设置一个基于session的localeResolver，能够让其在session期间能够请求
     * 到同样的locale
     * @return
     */
    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        if (lci != null) {
            return lci;
        }

        lci = new LocaleChangeInterceptor();
        lci.setParamName("language");

        return lci;
    }

    /**
     * Locale resolver locale resolver.
     *
     * @return the locale resolver
     */
    @Bean("localeResolver")
    public LocaleResolver localeResolver() {

        // 设置基于session的localeResolver，并设置默认的语言
        // 其中，LocaleResolver默认是AcceptHeaderLocaleResolver
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);

        return slr;
    }
}
